package com.application.lucky.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.lucky.R;
import com.application.lucky.activity.me.PlayTypeActivity;
import com.application.lucky.activity.me.RechargeCardActivity;
import com.application.lucky.activity.me.TIXianActivity;
import com.application.lucky.bean.eventbean.GroupClearUnReadEvent;
import com.application.lucky.bean.eventbean.LeaveRoomEvent;
import com.application.lucky.bean.eventbean.MessageEvent;
import com.application.lucky.bean.jsonBean.BaseWebBean;
import com.application.lucky.bean.jsonBean.ChaZhangBean;
import com.application.lucky.bean.jsonBean.HistoryBean;
import com.application.lucky.bean.jsonBean.RedPListbean;
import com.application.lucky.bean.jsonBean.RoomInfoBean;
import com.application.lucky.bean.jsonBean.WebBean;
import com.application.lucky.bean.jsonBean.WebJoinBean;
import com.application.lucky.bean.jsonBean.WebMessageBean;
import com.application.lucky.bean.uibean.GroupChatUiBean;
import com.application.lucky.config.Config;
import com.application.lucky.manager.SocketListenerManager;
import com.application.lucky.manager.UserManagers;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.RedPRequest;
import com.application.lucky.request.nav.UrlManager;
import com.application.lucky.utils.CTextUtils;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.dialog.TwoButtonDialog;
import com.application.mylibrary.utils.DateUtils;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.LogUtils;
import com.application.mylibrary.utils.ToastUtils;
import com.application.mylibrary.widget.RefreshView;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.effective.android.panel.PanelSwitchHelper;
import com.effective.android.panel.interfaces.listener.OnPanelChangeListener;
import com.effective.android.panel.view.PanelView;
import com.google.gson.Gson;
import com.qunar.im.base.common.ConversitionType;
import com.qunar.im.ui.util.MoneyUtils;
import com.qunar.im.ui.util.ProfileUtils;
import com.qunar.im.ui.view.IconView;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class GroupActivity extends Activity implements View.OnClickListener {

    private TitlebarView mTitleBar;
    private RecyclerView mRclView;
    private EditText mEditMsg;
    private IconView mTvEmojicon;
    private IconView mTvOptionsBtn;
    private RecyclerView mRclBottomPanel;
    private String id;
    private ChatListAdapter adapter;
    private String name;
    private RefreshView refreshView;
    private TwoButtonDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        id = intent.getStringExtra("id");
        isSHow = true;

        super.onCreate(savedInstanceState);
        EventBusUtils.register(this);
        setContentView(R.layout.activity_group_new);
        UserManagers.getInstance().loadPayPw();
        initView();
        initListener();

        EventBusUtils.postSticky(new GroupClearUnReadEvent(id));
    }

    public static boolean isSHow;

    private void initWebSocket() {
        WebSocketManager manager = SocketListenerManager.getInstance().getManager();
        //启动连接
        if (!manager.isConnect()) {
            manager.start();
        } else {
            if (WebSocketHandler.getDefault().isConnect()) {
                sendMessage("200", new WebJoinBean(UserManagers.getInstance().getUserId(), GroupActivity.this.id));
            } else {
                WebSocketHandler.getDefault().reconnect();
            }

        }


        //注意，需要在 AndroidManifest 中配置网络状态获取权限
        //注册网路连接状态变化广播
        WebSocketHandler.registerNetworkChangedReceiver(this);


        WebSocketHandler.getDefault().addListener(SocketListenerManager.getInstance().getSocketListener());
    }


    private void initListener() {
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {

                finish();
                overridePendingTransition(0, 0);
            }

            @Override
            public void rightClick() {
                Intent intent = new Intent(GroupActivity.this, GroupCenterActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("data", dataInfo);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                GroupChatUiBean item = GroupActivity.this.adapter.getItem(position);
                if (item != null) {
                    if (item.getItemType() != GroupChatUiBean.TYPE_system) {
                        if (dataInfo != null) {
                            Intent intent = new Intent(GroupActivity.this, RedPContentActivity.class);
                            intent.putExtra("data", item.rightbean);
                            startActivity(intent);
                            overridePendingTransition(0, 0);
                        }
                    }
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mHelper != null) {
                    mHelper.resetState();
                }
            }
        });


    }

    public void sendMessage(String command, BaseWebBean b) {
        WebBean<BaseWebBean> handBeanWebBean = new WebBean<>();
        handBeanWebBean.data = b;
        handBeanWebBean.command = command;
        String s = JSON.toJSONString(handBeanWebBean);
        LogUtils.i("lucky_log  sendMessage(String, T):" + s);
        WebSocketHandler.getDefault().send(s);
    }

//    private Runnable mScrollToBottomRunnable;

    private void initView() {
        SocketListenerManager.getInstance().clearUnRead(id);
        mTitleBar = (TitlebarView) findViewById(R.id.title_bar);
        mRclView = (RecyclerView) findViewById(R.id.rcl_view);
        mTitleBar.setTitle(name);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);//列表再底部开始展示，反转后由上面开始展示
        layoutManager.setReverseLayout(true);
        mRclView.setLayoutManager(layoutManager);

        adapter = new ChatListAdapter(new ArrayList<GroupChatUiBean>());
        adapter.setRoomName(name);
        mRclView.setAdapter(adapter);
        mEditMsg = (EditText) findViewById(R.id.edit_msg);
        mTvEmojicon = (IconView) findViewById(R.id.tv_emojicon);
        mTvOptionsBtn = (IconView) findViewById(R.id.tv_options_btn);
        mRclBottomPanel = (RecyclerView) findViewById(R.id.rcl_bottom_panel);
        refreshView = ((RefreshView) findViewById(R.id.refresh_view));
        refreshView.setRefreshListener(new RefreshView.RefreshListener() {
            @Override
            public void onRefresh() {
                loadHistory();
            }
        });

        mEditMsg.setFocusable(false);

        mEditMsg.setFocusableInTouchMode(false);
        initList();
        initBottom();
        loadInfo();


    }

    private PanelSwitchHelper mHelper;

    @Override
    protected void onStart() {
        super.onStart();
        if (mHelper == null) {
            mHelper = new PanelSwitchHelper.Builder(this)
                    .bindPanelSwitchLayout(R.id.panel_switch_layout)        //Binding a panelSwitchLayout
                    .bindPanelContainerId(R.id.panel_container)             //Binding a contentContainer
                    .bindContentContainerId(R.id.content_view)
                    .addPanelChangeListener(new OnPanelChangeListener() {

                        @Override
                        public void onKeyboard() {

                        }

                        @Override
                        public void onNone() {

                        }

                        @Override
                        public void onPanel(PanelView view) {
                            scrollToBottom();
                        }

                        @Override
                        public void onPanelSizeChange(PanelView panelView, boolean portrait, int oldWidth, int oldHeight, int width, int height) {

                        }
                    })//Binding a panelContainer
                    .build();
        }
    }

    private void scrollToBottom() {
        if (adapter.getItemCount() > 0) {
            mRclView.scrollToPosition(0);
        }
//        mRclView.postDelayed(mScrollToBottomRunnable, 300);
    }

    private RoomInfoBean dataInfo;

    private void loadInfo() {
        initWebSocket();
        joinRoom();
        List<RedPListbean> message = SocketListenerManager.getInstance().getMessage(id);
        if (message != null && !message.isEmpty()) {
            for (RedPListbean webMessageBean : message) {
                addNewMessage(webMessageBean);
            }
            scrollToBottom();
        }
        new RedPRequest().red_join_room(id, new CallBackEx<BaseResponse<RoomInfoBean>>() {
            @Override
            public void onSuccess(BaseResponse<RoomInfoBean> stringBaseResponse) {
                dataInfo = stringBaseResponse.dataInfo;

//                loadHistory();

            }

            @Override
            public void onFailed(int code) {

            }
        });
    }

    private void joinRoom() {
        new RedPRequest().relation_group_join(id, new CallBackEx<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> stringBaseResponse) {

            }

            @Override
            public void onFailed(int code) {

            }
        });
    }

    private int index;
    long time;

    private void loadHistory() {

        List<RedPListbean> message = SocketListenerManager.getInstance().getMessage(id);

        if (message.size() > 0) {
            RedPListbean redPListbean = message.get(0);
            if (redPListbean != null) {
                time = redPListbean.getCreateTime();
            }
        }
        if (dataInfo != null) {
            String roomId = dataInfo.getRoomId();

            new RedPRequest().red_room_history(index, roomId, new CallBackEx<BaseResponse<HistoryBean>>() {
                @Override
                public void onFailed(int code) {
                    if (isFinishing()) {
                        return;
                    }
                    refreshView.setFinish();
                }

                @Override
                public void onSuccess(BaseResponse<HistoryBean> baseResponse) {
                    if (isFinishing()) {
                        return;
                    }
                    refreshView.setFinish();
                    HistoryBean dataInfo = baseResponse.dataInfo;
                    List<RedPListbean> list = dataInfo.getList();
                    for (int i = 0; i < list.size(); i++) {

                        RedPListbean data1 = list.get(i);
                        if (data1 == null) {
                            break;
                        }
                        if (data1.getCreateTime() / 1000 < time / 1000) {
                            GroupChatUiBean bean;
                            bean = new GroupChatUiBean(GroupChatUiBean.TYPE_RIGHT);
                            if (data1.isMatch()) {
                                GroupChatUiBean system = new GroupChatUiBean(GroupChatUiBean.TYPE_system);
                                system.rightbean = data1;
                                adapter.addData(system);
                            }

                            bean.isOPen = true;
                            bean.rightbean = data1;
                            bean.time = data1.getCreateTime();
                            adapter.addData(bean);
                        }

                    }

                    index += list.size();
                }

            });
        }
    }


    private void initBottom() {


        mRclBottomPanel.setLayoutManager(new GridLayoutManager(this, 4));
        BottomPanelAdapter bottomPanelAdapter = new BottomPanelAdapter(R.layout.item_group_bottom_panel);
        bottomPanelAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0://红包
                        if (!UserManagers.getInstance().isSetPayPW()) {
                            dialog = new TwoButtonDialog.Build(GroupActivity.this)
                                    .disMiss(true)
                                    .setMessage("请先设置支付密码！")
                                    .setLeftButton("取消", null)
                                    .setRightButton("确定", new TwoButtonDialog.BaseDialogClickListener() {
                                        @Override
                                        public void click() {
                                            dialog.dismiss();
                                            startActivity(new Intent(GroupActivity.this, SetPayPawwordActivity.class));
                                            overridePendingTransition(0, 0);
                                        }
                                    })
                                    .create();
                            dialog.show();
                            return;
                        }

                        if (dataInfo != null) {
                            Intent intent = new Intent(GroupActivity.this, SendRedPActivity.class);
                            intent.putExtra("id", dataInfo.getRoomId());
                            intent.putExtra("name", name);
                            startActivityForResult(intent, Send_RP);
                            overridePendingTransition(0, 0);
                        }

                        break;
                    case 1://充值
                        startActivity(new Intent(GroupActivity.this, RechargeCardActivity.class));
                        overridePendingTransition(0, 0);
                        break;
                    case 2://提现
                        startActivity(new Intent(GroupActivity.this, TIXianActivity.class));
                        overridePendingTransition(0, 0);
                        break;
                    case 3://客服
                        Intent intent = new Intent(GroupActivity.this, PbChatActivity.class);
                        intent.putExtra(PbChatActivity.KEY_JID, Config.IMIdUtils.getIMUid(Config.KEFU_ID));
                        intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, String.valueOf(ConversitionType.MSG_TYPE_CHAT));
                        intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);
                        startActivity(intent);
                        overridePendingTransition(0, 0);
//                        startActivityAnim(new Intent(GroupActivity.this, KeFuActivity.class));
                        break;
                    case 4://查账
                        loadChaZhang();
//                        startActivityAnim(new Intent(GroupActivity.this, MoneyHistoryActivity.class));

                        break;
                    case 5://玩法
                        startActivity(new Intent(GroupActivity.this, PlayTypeActivity.class));
                        overridePendingTransition(0, 0);


                }
            }
        });
        List<String> datas = new ArrayList<>();
        datas.add("红包");
        datas.add("充值");
        datas.add("提现");
        datas.add("客服");
        datas.add("查账");
        datas.add("玩法");
        bottomPanelAdapter.setNewData(datas);
        mRclBottomPanel.setAdapter(bottomPanelAdapter);
    }

    private void loadChaZhang() {
        if (dataInfo!=null) {
            new RedPRequest().red_accounts_check(dataInfo.getRoomId(),new CallBackEx<BaseResponse<ChaZhangBean>>() {
                @Override
                public void onSuccess(BaseResponse<ChaZhangBean> stringBaseResponse) {
                    GroupChatUiBean bean = new GroupChatUiBean(GroupChatUiBean.TYPE_CHAZHANG);
                    ChaZhangBean dataInfo = stringBaseResponse.dataInfo;

                    if (dataInfo != null) {
                        dataInfo.name = UserManagers.getInstance().getShowName();
                        bean.bean = dataInfo;
                        adapter.addData(0, bean);
                        scrollToBottom();


                        RedPListbean redPListbean = new RedPListbean();
                        redPListbean.bean = dataInfo;
                        SocketListenerManager.getInstance().addGroup(id, redPListbean);


                        WebMessageBean webMessageBean = new WebMessageBean();
                        webMessageBean.from = UserManagers.getInstance().getUserId();
                        webMessageBean.groupId = id;
                        webMessageBean.messageType = "10086";
                        webMessageBean.message = new Gson().toJson(redPListbean);

                        new RedPRequest().sendMessage(webMessageBean);
                    }

                }

                @Override
                public void onFailed(int code) {

                }
            });
        }

    }

    private void initList() {
        mEditMsg.setOnClickListener(this);
        mTvEmojicon.setOnClickListener(this);
        mTvOptionsBtn.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_msg:
            case R.id.tv_emojicon:

                ToastUtils.show("该群组禁止发言");
                break;
            case R.id.tv_options_btn:

                break;

        }
    }

    @Override
    public void onBackPressed() {
        if (mHelper != null && mHelper.hookSystemBackForHindPanel()) {
            return;

        }
        finish();
        overridePendingTransition(0, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addRedPEvent(final RedPListbean data1) {
        SocketListenerManager.getInstance().addGroup(id, data1);
        GroupChatUiBean bean;
        if (TextUtils.equals(String.valueOf(data1.getUser().getUserId()), UserManagers.getInstance().getUserId())) {
            bean = new GroupChatUiBean(GroupChatUiBean.TYPE_RIGHT);
        } else {
            bean = new GroupChatUiBean(GroupChatUiBean.TYPE_LEFT);
        }

        bean.time = System.currentTimeMillis();
        if (data1 != null) {
            bean.rightbean = data1;
            bean.time = data1.getCreateTime();
            adapter.addData(0, bean);
            mRclView.smoothScrollToPosition(0);
//            List<RedPListbean.XuserInfoBeanListBean> xuserInfoBeanList = data1.getXuserInfoBeanList();
//            mCompositeDisposable.add(Observable.delay(0, xuserInfoBeanList.size(), 0, 3000 / xuserInfoBeanList.size(), TimeUnit.MILLISECONDS)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribeWith(getObserver(data1)));
            mRclView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    adapter.openRed(data1.getCreateTime());
                    if (data1.isMatch()) {
                        GroupChatUiBean system = new GroupChatUiBean(GroupChatUiBean.TYPE_system);
                        system.rightbean = data1;
                        adapter.addData(0, system);
                        mRclView.smoothScrollToPosition(0);
                    }
                }
            }, 1000);


        }

        WebMessageBean webMessageBean = new WebMessageBean();
        webMessageBean.from = UserManagers.getInstance().getUserId();
        webMessageBean.groupId = id;
        webMessageBean.messageType = "10086";
        webMessageBean.message = new Gson().toJson(data1);

        new RedPRequest().sendMessage(webMessageBean);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void leaveRoom(final LeaveRoomEvent data1) {
        SocketListenerManager.getInstance().clear(id);
        finish();
    }


    @Subscribe
    public void receiverMessage(MessageEvent e) {
        WebMessageBean webMessageBean = e.webMessageBean;
        if (webMessageBean != null) {
            String message1 = webMessageBean.message;
            RedPListbean listbean = new Gson().fromJson(message1, RedPListbean.class);
            if (listbean != null) {
                addNewMessage(listbean);

                scrollToBottom();
            }
        } else if (e.webMessageBeans != null) {
            boolean loadHIstory = SocketListenerManager.getInstance().getLoadHIstory(id);
            for (WebMessageBean messageBean : e.webMessageBeans) {
                if (!loadHIstory) {
                    String message1 = messageBean.message;
                    RedPListbean listbean = new Gson().fromJson(message1, RedPListbean.class);
                    addNewMessage(listbean);
                    SocketListenerManager.getInstance().addGroup(messageBean.groupId, listbean);
                }
            }
            SocketListenerManager.getInstance().setLoadHIstory(id);
            scrollToBottom();
        } else {
            String message = e.message;
            String userId = UserManagers.getInstance().getUserId();
            LogUtils.i("lucky_log  onMessage(String, T):" + message);
            JSONObject object = JSON.parseObject(message);
            String data = object.getString("data");
            String command = object.getString("command");
            switch (command) {
//                case "1"://握手成功  需要绑定用户信息
//                    //String id, String appId, String clientType, String token
//
//                    sendMessage("100", new WebUserbean(userId, "1", "200", userId));
//                    break;
                case "101"://绑定用户之后需要进入房间
                    sendMessage("200", new WebJoinBean(userId, GroupActivity.this.id));

            }

        }

    }

    private void addNewMessage(final RedPListbean data1) {
        if (data1==null) {
            return;
        }
        if (data1.bean != null) {
            GroupChatUiBean bean = new GroupChatUiBean(GroupChatUiBean.TYPE_CHAZHANG);
            bean.bean = data1.bean;
            adapter.addData(0, bean);
        } else {
            GroupChatUiBean bean;
            if (!TextUtils.equals(String.valueOf(data1.getUser().getUserId()), UserManagers.getInstance().getUserId())) {
                bean = new GroupChatUiBean(GroupChatUiBean.TYPE_LEFT);
            } else {
                bean = new GroupChatUiBean(GroupChatUiBean.TYPE_RIGHT);

            }
            bean.time = System.currentTimeMillis();
            bean.rightbean = data1;
            bean.isOPen = true;
            bean.time = data1.getCreateTime();
            adapter.addData(0, bean);
            if (data1.isMatch() && TextUtils.equals(String.valueOf(data1.getUser().getUserId()), UserManagers.getInstance().getUserId())) {
                GroupChatUiBean system = new GroupChatUiBean(GroupChatUiBean.TYPE_system);
                system.rightbean = data1;
                adapter.addData(0, system);
            }
//            }
        }
    }


    static class ChatListAdapter extends BaseMultiItemQuickAdapter<GroupChatUiBean, BaseViewHolder> {
        public String roomName;


        public String getRoomName() {
            return roomName;
        }

        public void setRoomName(String roomName) {
            this.roomName = roomName;
        }


        public ChatListAdapter(List<GroupChatUiBean> data) {
            super(data);
            addItemType(GroupChatUiBean.TYPE_LEFT, R.layout.item_group_rp_left);
            addItemType(GroupChatUiBean.TYPE_RIGHT, R.layout.item_group_rp_right);
            addItemType(GroupChatUiBean.TYPE_system, R.layout.item_group_rp_system);
            addItemType(GroupChatUiBean.TYPE_CHAZHANG, R.layout.item_group_cha_zhang);
        }

        public void addLoopData(List<GroupChatUiBean> list) {
            for (GroupChatUiBean bean : list) {
                mData.add(0, bean);
            }
            notifyDataSetChanged();
        }


        @Override
        protected void convert(BaseViewHolder helper, GroupChatUiBean item) {

            switch (helper.getItemViewType()) {
                case GroupChatUiBean.TYPE_LEFT:
                    bindLeft(helper, item);
                    break;
                case GroupChatUiBean.TYPE_RIGHT:
                    bindRight(helper, item);
                    break;
                case GroupChatUiBean.TYPE_system:
                    bindSystem(helper, item);
                    break;
                case GroupChatUiBean.TYPE_CHAZHANG:
                    binChaZhang(helper, item);
            }
        }

        private void binChaZhang(BaseViewHolder helper, GroupChatUiBean item) {
            ChaZhangBean bean = item.bean;
            if (bean != null) {
                helper.setText(R.id.tv_rp_shuying, "¥" + MoneyUtils.getMoney(bean.getRedRecord()))
                        .setText(R.id.tv_rb_name, bean.name)
                        .setText(R.id.tv_rp_jine, "¥" + MoneyUtils.getMoney(bean.getRedMoney()))
                        .setText(R.id.tv_rp_send_count, bean.getRedNum() + "")
                        .setText(R.id.tv_start_time, DateUtils.formBirthday(bean.getFirstTime()))
                        .setText(R.id.tv_end_time, DateUtils.formBirthday(bean.getLastTime()))
                        .setText(R.id.tv_rp_zhonglei_jine, "¥" + MoneyUtils.getMoney(bean.getRewardMoney()));

            }
        }


        private void bindSystem(BaseViewHolder helper, GroupChatUiBean item) {
            RedPListbean bean = item.rightbean;
//            double a =;
            helper.setText(R.id.tv_rp_money, "¥" + MoneyUtils.getMoney(bean.getMoney()));
            helper.setText(R.id.tv_rp_num, bean.getRedNum() + "包");

            helper.setText(R.id.tv_rp_type, roomName);
            helper.setText(R.id.tv_rb_name, UserManagers.getInstance().getShowName());

            List<Integer> xlist = bean.getXlist();
//            StringBuilder leidian = new StringBuilder();
            List<?> xmatchList = bean.getXmatchList();

//            if (xlist != null) {
//                for (Integer integer : xlist) {
//                    leidian.append(integer).append("/");
//                }
//            }
            CTextUtils.Builder builder = CTextUtils.getBuilder("");

            for (Integer integer : xlist) {
                if (item.isOPen) {
                    if (!xmatchList.contains(integer)) {
                        builder
                                .append(integer + "").append("/");
                    } else {
                        builder
                                .append(integer + "").setForegroundColor(Color.parseColor("#DE3F35")).append("/");
                    }
                } else {
                    builder
                            .append(integer + "").append("/");
                }

            }
            helper.setText(R.id.tv_rp_leidian, builder.create());
            helper.setText(R.id.tv_rp_leidian_num, bean.getXmatchList().size() + "");
            helper.setText(R.id.tv_rp_peilv, bean.getMultiple() + "");//赔率
            helper.setText(R.id.tv_rp_jiangli, "¥" + MoneyUtils.getMoney(bean.getRewardMoney()));

        }

        private void bindRight(BaseViewHolder helper, GroupChatUiBean item) {
            RedPListbean rightbean = item.rightbean;
            ImageView headVIew = helper.getView(R.id.iv_send_rb_headpic);
            headVIew.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            RedPListbean.UserBean user = rightbean.getUser();

            ProfileUtils.displayGravatarRoundedCornerByImageSrc(((Activity) mContext), UrlManager.getHeadPic(user.getHeadPic()), headVIew);
//            double a = rightbean.getMoney() / 10;
            helper.setText(R.id.tv_send_rb_num, "¥" + MoneyUtils.getMoney(rightbean.getMoney()));
            List<Integer> xlist = rightbean.getXlist();
//            StringBuilder leidian = new StringBuilder();
            List<?> xmatchList = rightbean.getXmatchList();

//            if (xlist != null) {
//                for (Integer integer : xlist) {
//                    leidian.append(integer).append("/");
//                }
//            }
            CTextUtils.Builder builder = CTextUtils.getBuilder("");

            for (Integer integer : xlist) {

                if (!xmatchList.contains(integer)) {
                    builder
                            .append(integer + "").append("/");
                } else {
                    if (item.isOPen) {
                        builder
                                .append(integer + "").setForegroundColor(Color.parseColor("#DE3F35")).append("/");
                    } else {
                        builder
                                .append(integer + "").append("/");
                    }

                }


            }
            helper.setText(R.id.tv_send_rp_lei, builder.create())

                    .setText(R.id.tv_send_rp_name, roomName != null ? roomName : "")
                    .setVisible(R.id.iv_send_rb_is_lei, item.isOPen && rightbean.isMatch())
                    .addOnClickListener(R.id.rl_send_rb_bg)
                    .setBackgroundRes(R.id.rl_send_rb_bg, item.isOPen ? R.drawable.chat_red_right_open : R.drawable.chat_red_right_nor)
                    .setText(R.id.tv_time, DateUtils.getRedTime(item.time));
        }

        private void bindLeft(BaseViewHolder helper, GroupChatUiBean item) {

            RedPListbean rightbean = item.rightbean;
            ImageView headVIew = helper.getView(R.id.iv_send_rb_headpic);
            headVIew.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            RedPListbean.UserBean user = rightbean.getUser();

            ProfileUtils.displayGravatarRoundedCornerByImageSrc(((Activity) mContext), UrlManager.getHeadPic(user.getHeadPic()), headVIew);
//            double a = rightbean.getMoney() / 10;
            helper.setText(R.id.tv_send_rp_num, "¥" + MoneyUtils.getMoney(rightbean.getMoney()));
            List<Integer> xlist = rightbean.getXlist();
//            StringBuilder leidian = new StringBuilder();
            List<?> xmatchList = rightbean.getXmatchList();

//            if (xlist != null) {
//                for (Integer integer : xlist) {
//                    leidian.append(integer).append("/");
//                }
//            }
            CTextUtils.Builder builder = CTextUtils.getBuilder("");

            for (Integer integer : xlist) {

                if (!xmatchList.contains(integer)) {
                    builder
                            .append(integer + "").append("/");
                } else {
                    if (item.isOPen) {
                        builder
                                .append(integer + "").setForegroundColor(Color.parseColor("#DE3F35")).append("/");
                    } else {
                        builder
                                .append(integer + "").append("/");
                    }
                }


            }
            helper.setText(R.id.tv_send_rp_lei, builder.create())
                    .setText(R.id.tv_send_rp_name, roomName != null ? roomName : "")
                    .setText(R.id.tv_name, user.getNickName())
                    .addOnClickListener(R.id.rl_send_rb_bg)
                    .setVisible(R.id.iv_send_rb_is_lei, rightbean.isMatch())
                    .setText(R.id.tv_time, DateUtils.getRedTime(item.time));
        }

        public void openRed(long time) {
            List<GroupChatUiBean> data = getData();
            for (int i = 0; i < data.size(); i++) {
                GroupChatUiBean groupChatUiBean = data.get(i);
                if (groupChatUiBean.time == time) {
                    groupChatUiBean.isOPen = true;
                    notifyDataSetChanged();
                }
            }

        }
    }

    public static final int Send_RP = 1;
    public static final int receiver_rp = 2;


//    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    ;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isSHow = false;
        SocketListenerManager.getInstance().setUnreadCount(id,0);

        EventBusUtils.unregister(this);
////        mCompositeDisposable.clear();
//        final WebSocketManager manager = WebSocketHandler.getDefault();
//        if (manager != null) {
////            manager.disConnect();
//        }

    }

//    private DisposableObserver getObserver(final RedPListbean data1) {
//
//        DisposableObserver disposableObserver = new DisposableObserver<Long>() {
//            @Override
//            public void onNext(Long o) {
////                if (data1 != null) {
////                    GroupChatUiBean left = new GroupChatUiBean(GroupChatUiBean.TYPE_LEFT);
////                    left.time = data1.getCreateTime() + 3000 / data1.getXuserInfoBeanList().size() * o;
////                    left.bean = data1.getXuserInfoBeanList().get(Integer.valueOf(o + ""));
////                    left.xlist = data1.getXlist();
////                    adapter.addData(left);
////                    mRclView.smoothScrollToPosition(adapter.getData().size());
////                }
//
//            }
//
//            @Override
//            public void onComplete() {
////                Log.d(id + TAG, "onComplete");
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
////                Log.e(id + TAG, e.toString(), e);
//            }
//        };

//        return disposableObserver;
//    }

    static class BottomPanelAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        int[] ress = {R.drawable.group_chat_send_red3, R.drawable.group_chat_chongzhi, R.drawable.group_chat_tixian, R.drawable.group_chat_service, R.drawable.group_chat_chazhang, R.drawable.group_chat_wanfa};


        public BottomPanelAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv, item)
                    .setImageResource(R.id.iv, ress[helper.getAdapterPosition()]);
        }
    }
}
